<?php

include_once "SqlResult.class.php" ;

class DBAccess {

	//SQL link_identifier, passed in on all calls to mysql_*
	private $connection;

	__construct( $server = NULL, $username = NULL, $password = NULL ){

		if( $server != NULL && $unername != NULL && $password != NULL ){
			$connection = mysql_pconnect( $server, $username, $password ) or die('Could not connect: ' mysql_error());
		}else{
			$connection = mysql_pconnect() or die('Could not connect: ' mysql_error());
		}
	}

	__destruct(){
		//if we're not using persistent connections, close the connection
		mysql_close( $connection );
	}

	// sanitize ( String ) -> String
	// sanitizes the string based on the connection
	public function sanitize( $string ){
		return mysql_real_escape_string( $string , $connection );
	}

	// insert ( SQL ) -> integer
	// runs the insert query on the database, and returns the last_insert_id
	public function insert( $sql ){
		if( strripos( $sql, "INSERT" ) < 0 ){
			//not an insert
			die("Not an insert query : " . $sql );
		}
		mysql_query( $sql, $connection ) or die("Couldn't complete query: " . $sql . " :: " . mysql_error());
		return mysql_insert_id( $connection );
	}

	//select ( SQL ) -> SqlResult | NULL
	// runs the sql select query, and
	// returns an SqlResult or NULL on error
	public function select( $sql ){
		$res = mysql_query( $sql, $connection );
		if( $res ){
			return new SqlResult( $res );
		}
		return null;
	}

	//modify ( SQL ) -> integer
	// runs the sql update/delete/drop,
	// and returns the number of rows modified, or -1 on error
	public function modify( $sql ){
		$result = mysql_query( $sql, $connection );
		if( ! $result ) {
			error_log( "Error running modification query : " . $sql . " :: " . mysql_error() );
			return -1;
		}
		return mysql_num_rows( $connection );
	}
}

?>
